package awk.datastruct.stack;

import java.util.Arrays;

/**
 * 顺序栈   数组作为底层实现
 * created with IDEA
 *
 * @author haifeng.wang
 * @since 2019-07-02-16:32
 */
public class SeqStack<E> {

    private Object[] stack;
    private int top;
    private int maxSize;

    public SeqStack() {
        this(10);
    }

    /**
     * 可以指定容量的构造函数
     */
    public SeqStack(int maxSize) {
        this.stack = new Object[maxSize];
        this.top = -1;
        this.maxSize = maxSize;
    }

    public static void main(String[] args) throws Exception {
        SeqStack<String> stack = new SeqStack<String>();
        stack.push("Rico");
        stack.push("TJU");
        stack.push("Livia");
        stack.push("NEU");

        System.out.println(stack);

        stack.pop();
        System.out.println(stack);

    }

    public boolean isEmpty() {
        return top == -1;
    }

    /**
     * 弹出并删除栈顶元素
     */
    @SuppressWarnings("unchecked")
    public E pop() throws Exception {
        if (top == -1) {
            throw new Exception("栈为空...");
        }
        E element = (E)stack[top];
        // 删除该元素
        stack[top--] = null;
        return element;
    }


    public void push(E e) throws Exception {
        if (top == maxSize - 1) {
            throw new Exception("栈已满...");
        }
        stack[++top] = e;
    }


    @Override
    public String toString() {
        return Arrays.toString(stack);
    }
}
